//
//  HJLoginVC.m
//  project
//
//  Created by hu on 2019/3/20.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJLoginVC.h"
#import "HJPerfectInfomationVC.h"
#import "HJTabBarViewController.h"
#import "HJRCIMManager.h"
#import "YFMobManager.h"
#import "JGProgressHUD.h"
#import "HJWebViewController.h"
#import "HJNavigationViewController.h"
#import "OpenInstallSDK.h"


@interface HJLoginVC ()<UITextFieldDelegate>

/**
 title
 */
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

/**
 手机号输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;

/**
 发送验证码按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *smsCodeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *phoneImageView;

/**
 验证码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *smsCodeTF;
@property (weak, nonatomic) IBOutlet UIImageView *smsCodeImageView;

/**
 登录按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (nonatomic, assign) NSInteger timeout;// 倒计时

/**
 同意按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

/**
 版权声明
 */
@property (weak, nonatomic) IBOutlet UIButton *RightBtn;

/**
 隐私保护
 */
@property (weak, nonatomic) IBOutlet UIButton *privacyBtn;

/**
 三方授权登录
 */
@property (nonatomic,strong) NSString *openJson;
/**
 openID
 */
@property (nonatomic,strong) NSString *openID;
@end

@implementation HJLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor redColor];
    self.phoneNum.delegate = self;
    self.smsCodeTF.delegate = self;
    [self configTextFieldRac];//根据键盘输入时时更改UI
    [self configBtnSmsCode];// 验证码RAC
    [self configBtnSubmit]; // 登录按钮
    // 视图按钮点击事件
    [self viewAllBtnClicked];

    [self.view setBackgroundColor:[UIColor whiteColor]];
}

#pragma mark -- 第一次安装从openinstall调接口
-(void)getInstallParamsImmediately {
    [[OpenInstallSDK defaultManager] getInstallParmsCompleted:^(OpeninstallData*_Nullable appData) {
        NSString * url = [Api stringByAppendingString:ShareCallbackApi];
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic addEntriesFromDictionary:appData.data];
        [HJHttpTool get:url params:dic success:^(HJResponeds *result) {
            LKLog(@"%@",result.data);
        } failure:^(id result) {
            LKLog(@"%@",result);
        }];
    }];
}

#pragma mark ——根据键盘输入时时更改UI
- (void)configTextFieldRac {
    @weakify(self)
    [[self.phoneNum.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=11;
    }] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.phoneNum.text = [x substringToIndex:11];
    }];
    
    [[self.smsCodeTF.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=6;
    }]subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.smsCodeTF.text = [x substringToIndex:6];
    }];
}

- (void)configBtnSmsCode {
    @weakify(self)
    RAC(self.smsCodeBtn, userInteractionEnabled) = [RACSignal combineLatest:@[self.phoneNum.rac_textSignal] reduce:^id(NSString *phone) {
        @strongify(self)
        if ([CommonTools isMobileNumber:phone]) {
            if (self->_timeout <= 0) { // 上一个验证码的倒计时已经结束 或未开始 才可以获取新的验证码
                self.smsCodeBtn.backgroundColor = [UIColor blackColor];
                self.smsCodeTF.userInteractionEnabled = YES;
                return @YES;
            } else {
                self.smsCodeTF.userInteractionEnabled = NO;
                return @NO;
            }
        }else {
            if (phone.length >=11) {
                [YFHud showError:@"您填写的手机号不正确!"];
            }
            self.smsCodeTF.userInteractionEnabled = NO;
            self.smsCodeBtn.backgroundColor = [UIColor lightGrayColor];
            self.loginBtn.backgroundColor = [UIColor lightGrayColor];
            return @NO;
        }
    }];
}

#pragma mark --创建RAC响应登录按钮是否可以点击
- (void)configBtnSubmit {
    @weakify(self)
    RAC(self.loginBtn,userInteractionEnabled) = [RACSignal combineLatest:@[self.phoneNum.rac_textSignal,self.smsCodeTF.rac_textSignal,RACObserve(self.agreeBtn, selected)] reduce:^id (NSString * phone, NSString * smsCode, NSNumber *select) {
        @strongify(self)
        if (phone.length ==11 && smsCode.length ==6 && [select boolValue]) {
            self.loginBtn.backgroundColor = [UIColor blackColor];
            return @YES;
        }
        self.loginBtn.backgroundColor = [UIColor lightGrayColor];
        return @NO;
    }];
}

#pragma mark -- 所有按钮点击事件
-(void)viewAllBtnClicked {
    @weakify(self)
    // 是否同意协议
    [[self.agreeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        x.selected = !x.selected;
        self.agreeBtn.selected = x.selected;
    }];
    
    // 版权声明
    [[self.RightBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        NSURL * url = [[NSBundle mainBundle] URLForResource:@"agreement.html" withExtension:nil];
        HJWebViewController * webVC =[HJWebViewController new];
        webVC.navTitle = @"乐见用户协议";
        webVC.isPushLogin = YES;
        webVC.URLString = url.absoluteString;
        HJNavigationViewController * nav = [[HJNavigationViewController alloc]initWithRootViewController:webVC];
        [self presentViewController:nav animated:YES completion:nil];
    }];
    
    // 隐私保护
    [[self.privacyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        HJWebViewController * webVC =[HJWebViewController new];
        webVC.navTitle = @"乐见隐私保护政策";
        webVC.isPushLogin = YES;
        webVC.URLString = @"http://www.lejianyou.com/yinsixieyi.html";
        HJNavigationViewController * nav = [[HJNavigationViewController alloc]initWithRootViewController:webVC];
        [self presentViewController:nav animated:YES completion:nil];
    }];
    
    /**
     验证码
     */
    [[self.smsCodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self.view endEditing:NO];
        [self countDown:x];
        [self HTTPSmsCode];
    }];
    
    /**
     登录
     */
    [[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self loginDidClicked];
    }];
}


#pragma mark --发送验证码
- (void)HTTPSmsCode {
    @weakify(self)
    NSString * smsCodeUrl = [Api stringByAppendingString:SmsApi];
    [HJHttpTool get:smsCodeUrl params:@{@"userName":self.phoneNum.text} success:^(HJResponeds *result) {
        LKLog(@"发送成功");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [YFHud showSuccess:@"发送成功"];
        });
    } failure:^(id result) {
        @strongify(self)
        [self showErrorHUDWithError:result];
    }];
}

// 登录按钮
- (void)loginDidClicked {
    NSString * url = [Api stringByAppendingString:LogiApi];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"code"] = self.smsCodeTF.text;
    params[@"userName"] = self.phoneNum.text;
    params[@"openJson"] = self.openJson;
    params[@"openId"] = self.openID;
    @weakify(self)
    if ([self.loginBtn.titleLabel.text isEqualToString:@"绑定手机号"]) {
        [YFHud showProgress:@"绑定中"];
    }else {
        [YFHud showProgress:@"登录中"];
    }
    [HJHttpTool post:url params:params success:^(HJResponeds *result) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self)
            [YFHud dismiss];
            LKLog(@"%@",result.data);
            [HJUserManager setUserModelWithDict:result.data];
            [[HJRCIMManager manager] connetRIM];
            if (result.code == 1103) {
                [self getInstallParamsImmediately];
                HJPerfectInfomationVC * perfectVC = [[HJPerfectInfomationVC alloc]init];
                perfectVC.islogin = YES;
                [self presentViewController:perfectVC animated:YES completion:nil];
                return;
            }else if (result.code == 1106) {
                self.titleLabel.text = @"绑定手机";
                [self.loginBtn setTitle:@"绑定手机号" forState:0];
                return;
            }
            [mUserDefaults setObject:@"1" forKey:@"isLogin"];
            [mUserDefaults setObject:[HJUserManager getUserModel].token forKey:@"token"];
            [UIApplication sharedApplication].keyWindow.rootViewController = [[HJTabBarViewController alloc] init];
            [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
        });
    } failure:^(id result) {
        [YFHud dismiss];
        [YFHud showError:result];
    }];
}

// 三方登录按钮 tag qq=111 微信=112 新浪=113
- (IBAction)threeLoginBtnClicked:(UIButton *)sender {
    NSLog(@"%zd",sender.tag);
    @weakify(self)
    switch (sender.tag) {
        case 111:
        {
            [YFMobManager authorize:YFMobPlatformQQ completion:^(BOOL isSuccess, SSDKUser * _Nullable userInfo, NSString * _Nullable message) {
                @strongify(self)
                self.openJson = [userInfo.rawData yy_modelToJSONString];
                self.openID = userInfo.uid;
                [self loginDidClicked];
            }];
        }
            break;
        case 112:
        {
            [YFMobManager authorize:YFMobPlatformWechat completion:^(BOOL isSuccess, SSDKUser * _Nullable userInfo, NSString * _Nullable message) {
                @strongify(self)
                self.openJson = [userInfo.rawData yy_modelToJSONString];
                self.openID = userInfo.uid;
                [self loginDidClicked];
            }];
        }
            break;
        case 113:
        {
            [YFMobManager authorize:YFMobPlatformSina completion:^(BOOL isSuccess, SSDKUser * _Nullable userInfo, NSString * _Nullable message) {
                @strongify(self)
                self.openJson = [userInfo.rawData yy_modelToJSONString];
                self.openID = userInfo.uid;
                [self loginDidClicked];
            }];
        }
            break;
        default:
            break;
    }
}


#pragma mark - Private Methods
- (void)countDown:(UIButton *)btn {
    _timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (self->_timeout <= 0) {
            // 倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.backgroundColor = [UIColor blackColor];
                btn.userInteractionEnabled = YES;
                [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"重新发送(%.2ld)", (long)self->_timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.smsCodeTF.userInteractionEnabled = YES;
                [btn setTitle:strTime forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
                btn.backgroundColor = [UIColor lightGrayColor];
            });
            self->_timeout--;
        }
    });
    dispatch_resume(_timer);
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag ==121313) {
        self.phoneImageView.image = self.phoneNum.text.length >0 ? setImage(@"phone_s_icon") : setImage(@"phone_icon");
    }else {
        self.smsCodeImageView.image = self.smsCodeTF.text.length >0 ? setImage(@"code_s_icon") : setImage(@"code_icon");
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag ==121313) {
         self.phoneImageView.image = textField.isFirstResponder ? setImage(@"phone_s_icon"): setImage(@"phone_icon");
    }else {
        self.smsCodeImageView.image = textField.isFirstResponder ? setImage(@"code_s_icon") : setImage(@"code_icon");
    }
}
@end
